﻿using System;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;

namespace Harvest.Api.Types
{

    public struct NullableInt : IXmlSerializable
    {

        private int _value;
        private bool _hasValue;


        private NullableInt(int value)
        {
            _hasValue = true;
            _value = value;
        }

        public bool HasValue
        {
            get { return _hasValue; }
        }

        public int Value
        {
            get { return _value; }
        }

        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader.GetAttribute("nil") == "true")
            {
                ReadNullValue();
                return;
            }
            ReadNonNullValue(reader);
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            //throw new NotSupportedException();
        }

        private void ReadNullValue()
        {
            _hasValue = false;
        }

        private void ReadNonNullValue(XmlReader reader)
        {
            reader.ReadStartElement();
            var s = reader.ReadString();
            _value = Convert.ToInt32(s);
            reader.ReadEndElement();
            _hasValue = true;
        }

        public static implicit operator NullableInt(int value)
        {
            return new NullableInt(value);
        }
    }

}
